package com.ccc.boot.mybatisplus;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * MyBatis Plus 自动填充
 *
 * @author superC
 * @date 2022/3/24
 * @version 0.1.0
 */
@Component
public class MyMetaObjectHandle implements MetaObjectHandler {

    /**
     * 通用字段：创建时间
     */
    private static final String CREATE_TIME = "createTime";

    /**
     * 通用字段：更新时间
     */
    private static final String UPDATE_TIME = "updateTime";

    @Override
    public void insertFill(MetaObject metaObject) {
        // 判断是否有相关通用字段
        boolean hasCreateTime = metaObject.hasSetter(CREATE_TIME);
        boolean hasUpdateTime = metaObject.hasSetter(UPDATE_TIME);

        // 有通用字段且值不为null，则自动填充
        if (hasCreateTime) {
            strictInsertFill(metaObject, CREATE_TIME, LocalDateTime.class, LocalDateTime.now());
        }
        if (hasUpdateTime) {
            strictInsertFill(metaObject, UPDATE_TIME, LocalDateTime.class, LocalDateTime.now());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 跳过null判断，强制更新updateTime为当前时间
        setFieldValByName(UPDATE_TIME, LocalDateTime.now(), metaObject);
    }

}